//import CostItem from "../controller/ui/cost_items"

import { Skill } from "../class/skill"
import JsonManager from "../manager/json_manager"
import StorageManager from "../manager/storage_manager"
import { Emitter } from "../utils/emmiter"
import { MessageType } from "../utils/message"
import { Utils } from "../utils/utils"

// import UIAnimaManager from "../manager/action_manager"

const { ccclass, property } = cc._decorator

interface OkCalBack {
    (isOK: boolean, param?: {}): void
}

@ccclass
export default class ChooseSkillUIManager extends cc.Component {
    static instance: ChooseSkillUIManager = null

    @property(cc.Node)
    uiNode: cc.Node = null

    @property(cc.Node)
    maskNode: cc.Node = null

    @property(cc.Label)
    labelTitle: cc.Label = null

    @property(cc.Label)
    labelDesc: cc.Label = null

    @property(cc.Button)
    btn1: cc.Button = null


    @property(cc.Button)
    btn2: cc.Button = null


    @property(cc.Button)
    btn3: cc.Button = null
    @property(cc.Button)
    buttonConfirm: cc.Button = null

    @property(cc.Label)
    labelCancel: cc.Label = null
    @property(cc.Label)
    labelConfirm: cc.Label = null

    ids: string[] = []

    curCallBack: OkCalBack = null
    curParam: any = null


    _isClick: boolean = false

    onLoad() {
        // console.log("PoolManager Onload");
        ChooseSkillUIManager.instance = this

        //this.maskNode.on('click', this.hideUI, this);

        this.btn1.node.on("click", this.cancel1, this)
        this.btn2.node.on("click", this.cancel2, this)
        this.btn3.node.on("click", this.cancel3, this)
        // this.buttonConfirm.node.on("click", this.confirm, this)

        if (this.uiNode.active) {
            this.uiNode.active = false
        }
    }

    getSkills(skillArray, existSkillId, count = 3) {
        // 筛选符合规则的技能
        const availableSkills = skillArray.filter(skill => {
            // 没有前置技能的可以直接刷新
           
            // 如果有前置技能，必须确保 existSkillId 包含 preId
            if (skill.preId !== "0" && !existSkillId.includes(skill.preId)) {
                return false;
            }
            
            // 如果技能不可堆叠且 existSkillId 已包含该技能 ID，则不能刷新
            if (skill.canStack === 0 && existSkillId.includes(skill.id)) {
                return false;
            }
            if (skill.preId === "0") {
                return true;
            }
            return true;
        });

        // 随机选择不重复的技能
        const selectedSkills = [];
        const usedIds = new Set();

        while (selectedSkills.length < count && availableSkills.length > 0) {
            // 随机挑选一个技能
            const randomIndex = Math.floor(Math.random() * availableSkills.length);
            const skill = availableSkills[randomIndex];

            // 检查是否重复
            if (!usedIds.has(skill.id)) {
                selectedSkills.push(skill);
                usedIds.add(skill.id);
            }

            // 从可用列表中移除，避免重复选中
            availableSkills.splice(randomIndex, 1);
        }

        return selectedSkills;
    }



    showUI(title: string, desc: string, callback: OkCalBack = null, param: {} = null, isNormal: boolean = true, labels: string[] = null) {
        if (!this.uiNode.active) {
            this.uiNode.active = true
            //  UIAnimaManager.instance.showDialog(this.uiNode, this.maskNode)
        }

        cc.director.pause();
        // 获取 canStack 为 0 的 id
        const cantStackIds = Object.values(JsonManager.instance.getDataByName('skill'))
            .filter((item: Skill) => item.canStack === 0) // 筛选出 canStack 为 0 的项
            .map((item: Skill) => Number(item.id));              // 提取 id

        // 找到 skillIds 和 cantStackIds 的重叠部分
        const overlappingIds = Object.values(StorageManager.instance.skills).map(id => Number(id)).
            filter(id => cantStackIds.includes(id));


        let existIds = Object.values(JsonManager.instance.getDataByName('skill'))
            .filter((item: Skill) => item.preId == 0);


        // let nopreids2 = []
        // existIds.forEach((v: Skill) => {
        //     nopreids2.push(v.id)
        // })
        // let needPreIds = Object.values(JsonManager.instance.getDataByName('skill'))
        //     .filter((item: Skill) => item.preId != 0);
        // // 筛选 ids2 中满足条件的数据
        // cc.log('无需前置')
        // cc.log(nopreids2)
        // cc.log("要前置")
        // cc.log(needPreIds)
        // let chooseIds = StorageManager.instance.skills;
        // const validIds2 = needPreIds.filter((item: Skill) => chooseIds.includes(item.preId));

       
        let res = this.getSkills(Object.values(JsonManager.instance.getDataByName('skill')), StorageManager.instance.skills)
        
        let mergedIds = []
        res.forEach(v=>{
            mergedIds.push(v.id)
        })

        // mergedIds = mergedIds.filter(id => !overlappingIds.includes(id));

        console.log("合并后的 ids 列表:",);
        cc.log(mergedIds)
        this.ids = Utils.getArrRandomItemsByNum(mergedIds, 3);
        this.btn1.node.active = false;
        this.btn2.node.active = false;
        this.btn3.node.active = false;

        this.refreshUI()
        this.curParam = param
    }

    refreshUI() {
        let skills: Skill = JsonManager.instance.getDataByName('skill');

        if (this.ids.length >= 1) {

            this.btn1.getComponentInChildren(cc.Label).string = this.getStrBySkill(skills[this.ids[0]])
            this.btn1.node.active = true;
        }
        if (this.ids.length >= 2) {
            this.btn2.node.active = true;
            this.btn2.getComponentInChildren(cc.Label).string = this.getStrBySkill(skills[this.ids[1]])
        }
        if (this.ids.length >= 3) {
            this.btn3.node.active = true;
            this.btn3.getComponentInChildren(cc.Label).string = this.getStrBySkill(skills[this.ids[2]])
        }

    }

    getStrBySkill(skill) {
        return skill.name.replace("{0}", skill.damage);
    }

    cancel1() {
        cc.log('1')
        StorageManager.instance.skills.push(this.ids[0])
        this.notifyAdd()
        this.hideUI()
    }

    cancel2() {
        cc.log('pick up:' + this.ids[1])
        // cc.log(this.ids[1])
        StorageManager.instance.skills.push(this.ids[1])
        this.notifyAdd()

    }

    cancel3() {
        cc.log('3')
        StorageManager.instance.skills.push(this.ids[2])
        this.notifyAdd()
        this.hideUI()
    }

    notifyAdd() {
        Emitter.fire(MessageType.addSkill)
        this.hideUI()
    }

    confirm() {
        //console.log("确定")
        if (this._isClick) {
            return
        }
        this._isClick = true
        this.scheduleOnce(function () {
            this._isClick = false
        }, 0.2)

        if (this.curCallBack != null) {
            this.curCallBack(true, this.curParam)
        }
        this.hideUI()
    }
    hideUI() {
        this.uiNode.active = false
        cc.director.resume();
        //  AudioManager.instance.playAudio('ui_close')

    }
}
